package cn.tianjindong.blog_manager.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.tianjindong.blog.common.pojo.PageView;
import cn.tianjindong.blog.pojo.BlogLink;
import cn.tianjindong.blog.pojo.BlogManager;
import cn.tianjindong.blog_manager.service.LinkService;

/**
 * 友情链接相关功能Controller
 * 
 * @author 田 金 东
 *
 */
@Controller
public class LinkController {

	@Autowired
	private LinkService linkService;

	/**
	 * 前往友情链接页面
	 * 
	 * @return
	 */
	@RequestMapping("/flink.html")
	public String toLinkPage(Model model, @RequestParam(defaultValue = "1") Integer currentPage,
			@RequestParam(defaultValue = "8") Integer countItem) {
		PageView<BlogLink> pageView = linkService.getLinkPageView(currentPage, countItem);
		model.addAttribute("pageView", pageView);
		return "/flink";
	}

	/**
	 * 前往友情链接添加页面
	 * 
	 * @return
	 */
	@RequestMapping("/add-flink.html")
	public String toAddLinkPage() {
		return "/add-flink";
	}

	/**
	 * 添加“友情链接”
	 * 
	 * @return
	 */
	@RequestMapping("/flink/add.action")
	public String addLink(HttpSession session, BlogLink link) {
		BlogManager user = (BlogManager) session.getAttribute("user");
		if (user != null) {
			linkService.addLink(link, user.getId());
			return "redirect:/flink.html";
		} else {
			return "redirect:/login.html";
		}
	}

	/**
	 * 前往“友情链接”更新页面
	 * 
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping("/flink/update/{id}.html")
	public String toUpdateLinkPage(Model model, @PathVariable Long id) {
		BlogLink link = linkService.getLinkById(id);
		model.addAttribute("link", link);
		return "/update-flink";
	}

	/**
	 * 更新“友情链接”
	 * @param link
	 * @return
	 */
	@RequestMapping("/flink/update.action")
	public String updateLink(BlogLink link) {
		linkService.updateLink(link);
		return "redirect:/flink.html";
	}

	/**
	 * 删除友情链接
	 * @param id
	 * @return
	 */
	@RequestMapping("/flink/delete/{id}.action")
	public @ResponseBody String deleteLink(@PathVariable Long id) {
		linkService.deleteLink(id);
		return null;
	}
}
